import { Modal, Form, Input, Button, Space, message, Radio, Select } from 'antd'
import http from '../api/http'
import type { ISportsItem } from '../types/sportsitem'
import { useEffect, useState } from 'react'

// 运动强度选项
const strengthOptions = [
  { id: '低', name: '低' },
  { id: '中', name: '中' },
  { id: '高', name: '高' }
]

// 适用性别选项
const genderOptions = [
  { id: 0, name: '男' },
  { id: 1, name: '女' },
  { id: 2, name: '通用' }
]

// 表单值类型定义（文本输入适配）
interface FormValues {
  code: string
  name: string
  Strength: string
  Stepeq: string
  Duration: string
  Minage: string
  Maxage: string
  Gender: number
  Parts: string
  Method: string
  Notes: string
}

interface Props {
  EditModalOpen: boolean
  EditHandleCancel: () => void
  onSuccess: () => void
  editData?: ISportsItem
}

const Edit: React.FC<Props> = ({ EditModalOpen, EditHandleCancel, onSuccess, editData }) => {
  const [form] = Form.useForm<FormValues>()
  const [submitError, setSubmitError] = useState<string>('')

  // 核心：初始化表单数据（确保修改时自动填充原有内容）
  useEffect(() => {
    // 仅当弹窗打开且有编辑数据时才初始化
    if (EditModalOpen && editData) {
      // 严格映射原有数据到表单（数字转字符串适配文本框）
      const initialData: FormValues = {
        code: editData.code || '',
        name: editData.name || '',
        Strength: editData.strength || '',
        Stepeq: editData.stepeq !== undefined ? editData.stepeq.toString() : '0',
        Duration: editData.duration !== undefined ? editData.duration.toString() : '30',
        Minage: editData.minage !== undefined ? editData.minage.toString() : '18',
        Maxage: editData.maxage !== undefined ? editData.maxage.toString() : '60',
        Gender: editData.gender !== undefined ? editData.gender : 2,
        Parts: editData.parts || '',
        Method: editData.method || '',
        Notes: editData.notes || ''
      }
      // 强制设置表单值（确保覆盖所有字段）
      form.setFieldsValue(initialData)
    } else if (!EditModalOpen) {
      // 弹窗关闭时重置表单，避免下次打开残留数据
      form.resetFields()
      setSubmitError('')
    }
  }, [EditModalOpen, editData, form]) // 依赖editData变化，确保数据更新

  // 提交修改
  const handleSubmit = async () => {
    setSubmitError('')
    try {
      const values = await form.validateFields() as FormValues

      if (!editData) {
        message.warning('未获取到待修改的运动项目数据')
        return
      }

      // 构建提交数据（字符串转数字，适配后端需求）
      const submitData: ISportsItem = {
        ...editData,
        ...values,
        Stepeq: Number(values.Stepeq),
        Duration: Number(values.Duration),
        Minage: Number(values.Minage),
        Maxage: Number(values.Maxage),
        id: editData.id // 确保ID正确传递
      }

      await http.put('sportsitem', submitData)
      message.success('修改成功')
      EditHandleCancel()
      form.resetFields()
      onSuccess()
    } catch (error: any) {
      const errorFields = error.errorFields || []
      if (errorFields.length > 0) {
        const firstError = errorFields[0]
        setSubmitError(`错误：${firstError.name.join('-')} - ${firstError.errors[0]}`)
      } else {
        setSubmitError('表单验证失败，请检查所有必填字段')
      }
      console.error('表单验证失败:', error)
    }
  }

  return (
    <Modal
      title={`修改运动项目（ID: ${editData?.id || ''}）`} // 显示ID，明确当前修改项
      open={EditModalOpen}
      onCancel={EditHandleCancel}
      centered
      footer={[
        <Button key="cancel" onClick={EditHandleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认修改
        </Button>
      ]}
      destroyOnClose={true}
      width={700}
      disabled={!editData}
    >
      {/* 显示具体错误信息 */}
      {submitError && (
        <div style={{ color: '#ff4d4f', marginBottom: 16, fontSize: 14 }}>
          {submitError}
        </div>
      )}

      <Form<FormValues>
        form={form}
        layout="vertical"
        scrollToFirstError // 验证失败时自动滚动到错误字段
        // 初始值仅作为默认，会被editData覆盖
        initialValues={{
          Gender: 2,
          Stepeq: '0',
          Duration: '30',
          Minage: '18',
          Maxage: '60'
        }}
      >
        <Space style={{ width: '100%' }}>
          <Form.Item
            name="code"
            label="运动编码"
            rules={[
              { required: true, message: '请输入运动编码' },
              { pattern: /^[A-Za-z0-9]+$/, message: '编码只能包含字母和数字' }
            ]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：YD001" disabled={!!editData?.id} />
          </Form.Item>

          <Form.Item
            name="name"
            label="运动名称"
            rules={[
              { required: true, message: '请输入运动名称' },
              { min: 2, message: '名称至少2个字符' }
            ]}
            style={{ flex: 2 }}
          >
            <Input placeholder="请输入运动项目名称" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="Strength"
            label="运动强度"
            rules={[{ required: true, message: '请选择运动强度' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Select placeholder="请选择运动强度">
              {strengthOptions.map(option => (
                <Select.Option key={option.id} value={option.id}>
                  {option.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="Stepeq"
            label="步数等效值"
            rules={[
              { required: true, message: '请输入步数等效值' },
              { pattern: /^\d+$/, message: '只能输入非负整数' }
            ]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：800" />
          </Form.Item>

          <Form.Item
            name="Duration"
            label="建议时长(分钟)"
            rules={[
              { required: true, message: '请输入建议时长' },
              { pattern: /^\d+$/, message: '只能输入正整数' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (Number(value) < 1) return Promise.reject(new Error('至少1分钟'))
                  return Promise.resolve()
                }
              })
            ]}
            style={{ flex: 1 }}
          >
            <Input placeholder="如：30" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="Minage"
            label="最小适用年龄"
            rules={[
              { required: true, message: '请输入最小适用年龄' },
              { pattern: /^\d+$/, message: '只能输入整数' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const num = Number(value)
                  if (num < 0 || num > 120) return Promise.reject(new Error('年龄范围0-120'))
                  return Promise.resolve()
                }
              })
            ]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：18" />
          </Form.Item>

          <Form.Item
            name="Maxage"
            label="最大适用年龄"
            rules={[
              { required: true, message: '请输入最大适用年龄' },
              { pattern: /^\d+$/, message: '只能输入整数' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const num = Number(value)
                  if (num < 0 || num > 120) return Promise.reject(new Error('年龄范围0-120'))
                  if (getFieldValue('Minage') && num < Number(getFieldValue('Minage'))) {
                    return Promise.reject(new Error('最大年龄不能小于最小年龄'))
                  }
                  return Promise.resolve()
                }
              })
            ]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：60" />
          </Form.Item>

          <Form.Item
            name="Gender"
            label="适用性别"
            rules={[{ required: true, message: '请选择适用性别' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              {genderOptions.map(gender => (
                <Radio key={gender.id} value={gender.id}>
                  {gender.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
        </Space>

        <Form.Item
          name="Parts"
          label="锻炼部位"
          rules={[
            { required: true, message: '请输入锻炼部位' },
            { min: 2, message: '至少2个字符' }
          ]}
        >
          <Input placeholder="如：腿部、核心肌群" />
        </Form.Item>

        <Form.Item
          name="Method"
          label="运动方法"
          rules={[
            { required: true, message: '请输入运动方法' },
            { min: 5, message: '至少5个字符' }
          ]}
        >
          <Input.TextArea rows={3} placeholder="请详细描述运动方法" />
        </Form.Item>

        <Form.Item
          name="Notes"
          label="注意事项"
          rules={[
            { required: true, message: '请输入注意事项' },
            { min: 5, message: '至少5个字符' }
          ]}
        >
          <Input.TextArea rows={3} placeholder="请输入运动注意事项" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export { Edit }